#include<iostream>
#include<pthread.h>
#include<cstdio>
#include<string>
#include<unistd.h>
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;




void* active(void* arg)
{
    std::string name = static_cast<const char*>(arg);//将arg转成字符类型
    while(true)
    {
        //Linux中一切皆文件(临界资源)，所以当所有的线程都向显示器中输入内容这件事情是不安全的
        pthread_mutex_lock(&mutex);
        //所有人进来之后都去同一个等待队列中等待

        pthread_cond_wait(&cond,&mutex);

        printf("%s is active!\n",name.c_str());
        pthread_mutex_unlock(&mutex);

    }
}



int main()
{
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,nullptr,active,(void*)"thread-1");
    pthread_create(&tid2,nullptr,active,(void*)"thread-2");
    pthread_create(&tid3,nullptr,active,(void*)"thread-3");
    
    sleep(1);
    printf("Main thread ctrl begin...\n");

    while(true)
    {
        printf("Main thread wakeup thread...\n");
        pthread_cond_signal(&cond);
  
        sleep(1);
    }

    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    pthread_join(tid3,nullptr);
    
    
    
    return 0;
}